package com.zwj.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwj.common.utils.PageUtils;
import com.zwj.common.utils.Query;

import com.zwj.gulimall.product.dao.CategoryDao;
import com.zwj.gulimall.product.entity.CategoryEntity;
import com.zwj.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> findListWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        // 获取所有一级菜单
        List<CategoryEntity> level1 = categoryEntities.stream().filter(
                categoryEntity -> {
                    return categoryEntity.getParentCid() == 0;
                }
        ).map(
                categoryEntity -> {
                    categoryEntity.setChildren(findChildren(categoryEntity, categoryEntities));
                    return categoryEntity;
                }
        ).sorted(
                (menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }
        ).collect(Collectors.toList());
        return level1;
    }

    @Override
    public void rmMenusByIds(List<Long> longs) {
        // TODO 查看这些菜单是否能删除

        baseMapper.deleteBatchIds(longs);
    }

    private List<CategoryEntity> findChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(
                (categoryEntity) -> {
                    return categoryEntity.getParentCid() == root.getCatId();
                }
        ).map(
                categoryEntity -> {
                    categoryEntity.setChildren(findChildren(categoryEntity, all));
                    return categoryEntity;
                }
        ).sorted(
                (menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }
        ).collect(Collectors.toList());
        return children;
    }

}